/**
 * 
 */
package me.joshua.tools4j.service;

import java.util.LinkedList;
import java.util.List;

import me.joshua.tools4j.dal.CheckPointRepository;
import me.joshua.tools4j.dal.SubscriptionRepository;
import me.joshua.tools4j.model.CheckPoint;
import me.joshua.tools4j.model.Subscription;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author <a href="mailto:daonan.zhan@gmail.com">Joshua Zhan</a>
 * 
 */
@Service
public class SubscriptionService {

	@Autowired
	private CrawlService				crawlService;
	@Autowired
	private SubscriptionRepository			subscriptionRepository;
	@Autowired
	private CheckPointRepository	checkPointRepository;

	public boolean check(String taskName) {
		taskName = StringUtils.trimToNull(taskName);
		if (null == taskName) {
			return false;
		}

		Subscription task = subscriptionRepository.findByName(taskName);
		return check(task);
	}

	/**
	 * 执行页面任务，检查是否有更新
	 * @param task
	 * @return 是否有更新
	 */
	public boolean check(Subscription task) {
		if (null == task) {
			return false;
		}
		String url = task.getUrl();
		String msgFormat = task.getMsgFormat();
		if (null == url || null == msgFormat) {
			return false;
		}

		Document doc = crawlService.crawl(url);
		if (null == doc) {
			return false;
		}

		List<CheckPoint> checkPoints = checkPointRepository.findBySubscriptionAndEnabledOrderByOrderAsc(task, true);
		if (CollectionUtils.isEmpty(checkPoints)) {
			return false;
		}

		List<String> results = new LinkedList<String>();
		for (CheckPoint checkPoint : checkPoints) {
			String result = check(doc, checkPoint);
			if (null == result) {
				result = StringUtils.EMPTY;
			}
			results.add(result);
		}

		String msg = String.format(msgFormat, results.toArray());
		task.setCurrentMsg(msg);
		if (StringUtils.equals(task.getCurrentMsg(), task.getLastMsg())) {
			return false;
		} else {
			task.setLastMsg(msg);
			subscriptionRepository.save(task);
			return true;
		}
		
	}

	private String check(Document doc, CheckPoint checkPoint) {
		String selector = StringUtils.trimToNull(checkPoint.getSelector());
		if (null == selector || null == doc) {
			return StringUtils.EMPTY;
		}

		Elements es = doc.select(selector);
		if (0 >= es.size()) {
			return StringUtils.EMPTY;
		}
		
		Element first = es.get(0);
		Integer type = checkPoint.getType();
		String value = null;
		
		// 根据类型获取元素内容
		if (type == CheckPoint.TYPE_A_HREF) {
			value = first.attr("href");
		} else {
			// Default is text content of element.
			value = first.text();
		}

		return value;
	}
}
